package practise.hibernate.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import practise.hibernate.dao.AddressDao;
import practise.hibernate.persistence.Address;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

@Service("addressDao")
@Repository
@Transactional
public class AddressDaoImpl implements AddressDao {
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional(readOnly = true)
    public List<Address> findAllAddresses(){

        final Query query = entityManager.createQuery("select distinct t from address t");
        return query.getResultList();
    }

    @Override
    @Transactional(readOnly = true)
    public List<Address> findByLocation(String location){
        final Query query = entityManager.createQuery("select distinct t from address t where t.location = :location");
        query.setParameter("location" , location);
        return query.getResultList();
    }

    @Override
    @Transactional(readOnly = false)
    public void deleteAddress(int id){
        entityManager.remove(entityManager.find(Address.class , id));
    }

    @Override
    @Transactional
    public Address merge(Address address){
        return entityManager.merge(address);
    }



}
